/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.web.service.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.vacoor.nothing.web.service.MailService;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.UnsupportedEncodingException;

/**
 * Simple mail send service
 *
 * @author vacoor
 */
// @Service
public class MailServiceImpl implements MailService {
    private static final Logger LOG = LoggerFactory.getLogger(MailServiceImpl.class);

    private JavaMailSender mailSender;
    private TaskExecutor taskExecutor;

    private String fromName;
    private String fromMail;

    @Override
    public void sendPlainMail(String[] to, String[] cc, String subject, String content) {
        cc = cc != null ? cc : new String[0];

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromMail);
        message.setTo(to);
        message.setCc(cc);
        message.setSubject(subject);
        message.setText(content);

        mailSender.send(message);
    }

    @Override
    public void sendHtmlMail(String[] to, String[] cc, String subject, String content, boolean async, File... attachments) {
        cc = cc != null ? cc : new String[0];
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(MimeUtility.encodeWord(fromName != null ? fromName : fromMail) + " <" + fromMail + ">");
            helper.setTo(to);
            helper.setCc(cc);
            helper.setSubject(subject);
            helper.setText(content, true);

            for (File file : attachments) {
                helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
            }

            if (!async) {
                mailSender.send(message);
            } else {
                addAsyncSendMailTask(message);
            }
        } catch (MessagingException e) {
            LOG.warn("send mail failed: {}", e);
        } catch (UnsupportedEncodingException e) {
            LOG.warn("send mail failed: {}", e);
        }
    }

    protected void addAsyncSendMailTask(final MimeMessage message) {
        taskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                mailSender.send(message);

                /*
                try {
                    Retry.on(MailSendException.class, 3, 500, new Retry.RetryCmd() {
                        @Override
                        public void call() throws Throwable {
                            mailSender.send(message);
                        }
                    });
                } catch (Throwable e) {
                    LOG.warn();
                }
                */
            }
        });
    }

    // ----------
    public void setFromMail(String fromMail) {
        this.fromMail = fromMail;
    }

    public void setFromName(String fromName) {
        this.fromName = fromName;
    }

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }
}
